package com.example.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.annotation.Order; // 用这个注解替代 Ordered 接口
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Order(-100) // 直接用注解指定顺序（值越小越先执行），无需实现 Ordered 接口
public class DynamicAuthFilter implements GlobalFilter { // 只实现 GlobalFilter 即可

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private DynamicWhitelistConfig whitelistConfig; // 注入动态白名单配置

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();

        // 2. 获取白名单并打印
        List<String> whitePaths = whitelistConfig.getPaths();

        // 3. 逐行匹配并打印过程
        boolean isWhite = false;
        for (String whitePath : whitePaths) {
            // 转换为正则（处理通配符）
            String regex = whitePath.replace("**", ".*").replace("*", "[^/]*");
            // 匹配当前路径
            boolean match = path.matches(regex);
            if (match) {
                isWhite = true;
                break;
            }
        }

        if (isWhite) {
            String token = request.getHeaders().getFirst("Authorization");
            System.out.println("打印token：" + token);
            if (token == null || token.isEmpty()) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            return chain.filter(exchange);
        }

        // 后续Token验证逻辑...
        System.out.println("路径 " + path + " 未匹配白名单，执行Token验证");

        //
//        // Token 验证逻辑（省略）

//
//        return chain.filter(exchange);

        // ...
        return unauthorized(exchange, "Invalid authentication token");
    }

    // 返回未授权响应
    private Mono<Void> unauthorized(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> errorBody = new HashMap<>();
        errorBody.put("code", HttpStatus.UNAUTHORIZED.value());
        errorBody.put("message", message);
        errorBody.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        try {
            DataBuffer buffer = response.bufferFactory()
                    .wrap(objectMapper.writeValueAsBytes(errorBody));
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            // 如果JSON处理失败，返回空响应
            return response.setComplete();
        }
    }

}